<template>
  <div class="app-container">
    <section>
      <div >
        <div
          style="font-size:20px;font-weight: bold;margin-bottom: 20px;text-align: center;display:inline-blok">
          其他出库订单
          <div style="margin-left:40px;display:inline">
          <el-button size="mini" v-show="hide" >草稿</el-button>
          <el-button size="mini" v-show="hides">已审核</el-button>
          </div>
          
        </div>
      </div>
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form
          :inline="true"
          ref="from"
          :model="from"
          label-width="80px"
          class="demo-form-inline"
        >
          <div class="tabel">
            <el-form-item label="订单编号:">
              <span>{{from.OrderNo}}</span>‘
            </el-form-item>
            <el-form-item label="仓库" prop="BranchId">
              <el-select v-model="from.BranchId" filterable placeholder="请选择到店铺">
                <el-option
                  v-for="item in StoreList"
                  :key="item.BranchId"
                  :label="item.BranchName"
                  :value="item.BranchId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="制单人:">
              <span>{{from.Creater}}</span>
            </el-form-item>
            <el-form-item label="制单时间:">
              <span>{{from.CreateDate}}</span>
            </el-form-item>
            <el-form-item label="摘要:">
              <el-input auto-complete="off" v-model="from.Summary"></el-input>
            </el-form-item>

            <el-form-item label="供应商" prop="SupplierId">
              <el-select v-model="from.SupplierId" filterable placeholder="请选择供应商">
                <el-option
                  v-for="item in SupplierList"
                  :key="item.SupplierId"
                  :label="item.SupplierName"
                  :value="item.SupplierId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-show="disappear" style="width:5%">
              <el-button type="primary" @click="UpdataAndAdd()">保存</el-button>
            </el-form-item>
            <el-form-item v-show="disappears" style="width:5%">
              <el-button
                type="success"
                @click="CheckPurchaseOrders()"
              >审核</el-button>
               </el-form-item>
            <el-form-item v-show="disappeard" style="width:5%">
              <el-button
                type="danger"
                @click="UnCheckPurchaseOrders()"
              >反审</el-button>
            </el-form-item>
             <el-form-item style="margin-left:400px" v-show="disappeara" > 
            <el-button type="primary" @click="handleEdit()" >新增商品</el-button>
          </el-form-item>
          </div>
         
        </el-form>
      </el-col>
      <el-table :data="List" border>
        <el-table-column prop="SKUName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
        <el-table-column prop="IsGift" label="赠品" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.IsGift" true-label="1" false-label="0"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="Qty" label="订货数量" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.Qty" size="mini" :precision="2" :step="0.1"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="SKUInPrice" label="进价" align="center"></el-table-column>
        <el-table-column prop="DiscountRate" label="折扣率" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.DiscountRate"
              size="mini"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="DiscountMoney" label="折扣额" align="center"></el-table-column>
        <el-table-column prop="ADMoney" label="折后金额" align="center"></el-table-column>
        <el-table-column prop="Remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.Remark" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="success" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          </template>
        </el-table-column>-->
      </el-table>
      <!-- 编辑 -->
      <el-dialog title="商品列表" :visible.sync="editFormVisible">
        <el-table
          :data="skulist"
          ref="multipleTable"
          border
          style="width: 100%; margin-top: 20px"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
        >
          <el-table-column type="selection" width="55" :reserve-selection="judge"></el-table-column>
          <el-table-column prop="ProductId" label="商品ID" align="center"></el-table-column>
          <el-table-column prop="SKUName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
          <el-table-column prop="SKUInPrice" sortable label="进价" align="center"></el-table-column>
        </el-table>
        <span slot="footer">
          <el-button @click="editFormVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="addSubmit()">确 定</el-button>
        </span>
        <div>
          <el-pagination
            background
            layout=" prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            :page-size="pageSize"
            :total="total"
            style="float:right;margin-top: 10px;"
          ></el-pagination>
        </div>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import {
  AddDeliveryOutStock,
  SKUList,
  GetPurchaseOrdersDetail,
  AddPurchaseOrders,
  GetPurchaseOrdersAdd,
  PurchaseGetSupplierList,
  FinanceStore,
  UpdateurchaseOrders,
  CheckPurchaseOrders,
  UnCheckPurchaseOrders
} from "@/api/api";
import Config from "../../api/config";
export default {
  data() {
    return {
      skulist: [],
      editFormVisible: false,
      page: 1,
      pagesize: 10,
      pageSize: 10,
      total: 0,
      judge:true,
      from: {
        OrderNo: "",
        Creater: "",
        Creater2: "",
        CreateDate: "",
        SupplierName: "",
        Summary: "",
        BillStatus: "",
        SupplierId: "",
        BranchName: ""
      },
      Data: [
        {
          ProductId: "",
          Unit: "",
          Qty: "",
          Inprice: "",
          Remark: ""
        }
      ],
      SupplierList: [],
      Id: "",
      List: [],
      StoreList: [],
      hide:true,//草稿
      hides:false,//已审核
      disappear:true,//保存
      disappears:false,//审核
      disappeard:false,//反审
      disappeara:true,//增加
    };
  },
  created() {
    this.getPurchaseOrders();
    this.PurchaseGetSupplierList();
    this.FinanceStore();
  },
  methods: {
    checkchange(IsGift) {
      this.Data.IsGift = IsGift;
      console.log(this.Data.IsGift);
    },

    //显示新增
    handleEdit: function() {
      this.editFormVisible = true;
      // this.clearSelect();
      console.log(this.List);
      this.getSkuList();
      //  this.judge = false;
    },
    //选择商品添加
    addSubmit() {
      var vdata = this.jsonspr;
      for (var j in vdata) {

        for (var i in this.List) {
          if (vdata[j].ProductId == this.List[i].ProductId) {
            vdata[j] = this.List[i];
          }
        }
      }
      this.List = vdata;
      console.log(this.List);
      this.editFormVisible = false;
    },
    //选择器
    getRowKeys(row) {
      return row.ProductId;
    },
     clearSelect () {
      this.$refs.multipleTable.clearSelection()
    },
    handleSelectionChange(val) {
     this.jsonspr = val;
      console.log("选择器", val);
      // this.select_orderId = [];
      // if (val) {
      //   val.forEach(row => {
      //     if (row) {
      //       this.select_orderId.push(row.ProductId);
      //     }
      //   });
      //   console.log("选择器", this.select_orderId);
      // }
    },

    getPurchaseOrders() {
      var POId = this.$route.query.POId;
      console.log("输出id", POId);
      if (POId != null) {
        this.GetPurchaseOrdersDetail();
      } else {
        this.GetPurchaseOrdersAdd();
        return;
      }
    },

    //有值的时候为修改，无值的时候添加
    UpdataAndAdd() {
      this.disappears=true;
      this.disappeara=false;
      var POId = this.$route.query.POId;
      console.log("输出id", POId);
      if (POId != null) {
        this.UpdateurchaseOrders();
      } else {
        this.AddPurchaseOrders();
        return;
      }
    },

    //获取商品以及表头
    GetPurchaseOrdersDetail() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        POId: this.$route.query.POId,
        Page: this.page,
        PageSize: this.pageSize
      };
      GetPurchaseOrdersDetail(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取采购订单表体列表");
          console.log(vdata);
          self.List = vdata.DataList;

          this.from.OrderNo = self.List[0].OrderNo;
          this.from.CreateDate = self.List[0].CreateDate;
          this.from.Creater = self.List[0].Creater;
          this.from.Summary = self.List[0].Summary;
          this.from.SupplierName = self.List[0].SupplierName;
          this.from.BillStatus = self.List[0].BillStatus;
          this.from.SupplierId = self.List[0].SupplierId;
          this.from.BranchId = self.List[0].BranchId;
        }
      });
    },

    //店铺下拉
    FinanceStore() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.page,
        PageSize: 20000
      };
      FinanceStore(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("店铺下拉");
          console.log(vdata);

          var list = vdata.DataList;
          self.StoreList = list;
        }
      });
    },

    //审核采购订单
    CheckPurchaseOrders() {
      this.disappear=false;
      this.disappears=false;
      this.disappeard=true;
      this.hide=false;
      this.hides=true;
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        POID: this.$route.query.POId
      };
      CheckPurchaseOrders(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.GetPurchaseOrdersDetail();
        }
      });
    },

    //反审
    UnCheckPurchaseOrders() {
      this.disappeard=false;
      this.disappear=true;
      this.disappeara=true;
      this.hide=true;
      this.hides=false;
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        POID: this.$route.query.POId
      };
      UnCheckPurchaseOrders(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.GetPurchaseOrdersDetail();
        }
      });
    },

    //获取采购表头(新增时)
    GetPurchaseOrdersAdd() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Exter: "PS"
      };
      GetPurchaseOrdersAdd(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取采购表头", vdata);
          this.from.OrderNo = vdata.OrderNo;
          this.from.CreateDate = vdata.dateTime;
          this.from.Creater = vdata.CreaterName;
          this.from.Creater2 = vdata.Creater;
        }
      });
    },

    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
    toggleSelection(row) {
      console.log("执行选择", row)
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    //新增采购列表
    AddPurchaseOrders() {
      var self = this;
      self.Data = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          InPrice: self.List[item].SKUSalePrice,
          Remark: self.List[item].Remark
        };
        self.Data.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        // Creater: this.from.Creater2,
        // SupplierId: this.from.SupplierId,
        Summary: this.from.Summary,
        OutBranchId: this.from.OutBranchId,
        InBranchId: this.from.InBranchId,
        Data: JSON.stringify(self.Data)
      };
      AddDeliveryOutStock(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
        }
      });
    },

    //修改采购订单
    UpdateurchaseOrders() {
      var self = this;
      self.Data = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          InPrice: self.List[item].SKUSalePrice,
          Remark: self.List[item].Remark
        };
        self.Data.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        // Creater: this.from.Creater2,
        // SupplierId: this.from.SupplierId,
        Summary: this.from.Summary,
        OutBranchId: this.from.OutBranchId,
        InBranchId: this.from.InBranchId,
        POID: this.$route.query.POId,
        Data: self.Data
      };
      UpdateurchaseOrders(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
        }
      });
    },

    //获取供应商列表
    PurchaseGetSupplierList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.page,
        PageSize: 20000
      };
      PurchaseGetSupplierList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取供应商列表", vdata);
          var list = vdata.DataList;
          self.SupplierList = list;
        }
      });
    },

    first1(rows) {
      this.$nextTick(() => {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      });
    },
    //获取商品列表
    getSkuList() {
      var self = this;
      console.log("输出选择项目", this.vdata);
      var para = {
        sessionid: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        page: this.page,
        pagesize: this.pagesize
      };
      SKUList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          self.skulist = list;
          this.total = vdata.TotalCount;
          // this.wids = res.data.result.wids                 //点击详情接口返回的 table里被选中的行的wids
          let a = []; //    res.data.result.wids.split(',')          //分割成数组
          self.List.forEach(res => {
            //把表格里所有的id加入到b里
            a.push(res.ProductId.toString());
          });
          console.log("1", a);
          let b = [];
          self.skulist.forEach(res => {
            //把表格里所有的id加入到b里
            b.push(res.ProductId.toString());
          });
          console.log("0", b);
          // console.log(typeof(b[0]))
          for (let c = 0; c < b.length; c++) {
            //对b循环  如果b里面有a（a是被选中的行） 则把索引代入到first函数里 让这些行的复选框选中
            // console.log(b[c])
            // console.log(a.indexOf(b[c]))
            if (b.indexOf(a[c]) >= 0) {
              console.log(a.indexOf(b[c]));
              self.first1([self.skulist[b.indexOf(a[c])]]);
            }
          }
        }
      });
    },
    //翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getSkuList();
    }
  }
};
</script>
<style scoped>
.tabel {
  display: inline-block;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 90%;
}
.tabel .el-form-item {
  width: 32%;
  /* letter-spacing:8px; */
}
.tabel .el-button {
  padding: 0 20px;
  height: 30px;
}
.el-form-item--medium .el-form-item__content,
.el-form-item--medium .el-form-item__label {
  color: black;
}
span {
  color: black;
}
</style>